// https://leetcode-cn.com/problems/invert-binary-tree/submissions/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 递归或者遍历就行了，只要确保每个节点的左右节点都交换
    
    // DFS递归
    // TreeNode* invertTree(TreeNode* root) {
    //     if (!root) return NULL;
    //     TreeNode* tmp = root->left;
    //     root->left = root->right;
    //     root->right = tmp;
    //     invertTree(root->left);
    //     invertTree(root->right);
    //     return root;
    // }

    // DFS非递归
    // TreeNode* invertTree(TreeNode* root) {
    //     if (!root) return NULL;
    //     stack<TreeNode*> s;
    //     s.push(root);
    //     while (!s.empty()) {
    //         TreeNode* top = s.top();
    //         s.pop();
    //         TreeNode* tmp = top->left;
    //         top->left = top->right;
    //         top->right = tmp;
    //         if (top->left) s.push(top->left);
    //         if (top->right) s.push(top->right);
    //     }
    //     return root;
    // }

    // BFS
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int len = q.size();
            for (int i = 0; i < len; ++i) {
                TreeNode* top = q.front();
                q.pop();
                TreeNode* tmp = top->left;
                top->left = top->right;
                top->right = tmp;
                if (top->left) q.push(top->left);
                if (top->right) q.push(top->right);
            }    
        }
        return root;
    }

};